package com.vhly.ddxdecompiler.dexreader.file;

import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-14
 * Time: 17:22:56
 *
 * @author vhly[FR]
 */
public class HeaderSection extends Section {

    private static final String MAGIC = "dex\n035\0";
    public static final int HEADER_SIZE = 112;
    private static final int ENDIAN_TAG = 0x12345678;

    int checkSum;
    int fileLen;
    int headerLen;
    int endTag;
    int linkSize;
    int linkOff;
    int mapOff;
    int dataSize;
    int dataOff;

    public HeaderSection(DexFile dexFile) {
        this.dexFile = dexFile;
    }

    public void read(DexInputStream din) throws IOException {
        byte[] magic = new byte[8];
        int len = din.read(magic);
        checkSum = din.readInt();
        byte[] sha1 = new byte[20];
        din.read(sha1, 0, 20);
        fileLen = din.readInt();
        headerLen = din.readInt();
        endTag = din.readInt();
        linkSize = din.readInt();
        linkOff = din.readInt();
        mapOff = din.readInt();


        // TODO read partdata
        dexFile.getStringIds().readHeaderPart(din);
        dexFile.getTypeIds().readHeaderPart(din);
        dexFile.getProtoIds().readHeaderPart(din);
        dexFile.getFieldIds().readHeaderPart(din);
        dexFile.getMethodIds().readHeaderPart(din);
        dexFile.getClassDefs().readHeaderPart(din);

        dataSize = din.readInt();

        dataOff = din.readInt();
        // TODO Read header finished
    }

    public void write(DataOutputStream dout) throws IOException {
        dout.writeBytes(MAGIC);
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("HeaderSection flen=").append(fileLen);
        return sb.toString();
    }
}
